<?php
namespace app\models;

use yii\base\Model;
use yii\web\UploadedFile;
use yii\imagine\Image;

class UploadForm extends Model
{
    /**
     * @var UploadedFile
     */
    public $file;
    private $_skip = false;
    private $_ext = 'png,jpg';
    const FILE_DIR = './uploads/';
    const SHOW_DIR = '/uploads/';
    const WATERMARK = './static/admin/images/watermark.png';

    public function rules()
    {
        return [
            [['file'], 'file', 'skipOnEmpty' => $this->_skip, 'extensions' => $this->_ext],
        ];
    }
    public function attributeLabels()
    {
        return [
            'file'=>'上传文件',
        ];
    }

    public function setSkip($skip = true){
        $this->_skip = $skip;
        return $this;
    }

    public function setExt($ext)
    {
        $this->_ext = $ext;
        return $this;
    }

    public function upload()
    {
        if ($this->validate()) {
            $file = $this->file;
            if($file){
                $file_name =  date('YmHis'.rand(10, 999999)) . '.' . $file->extension;
                $file->saveAs(self::FILE_DIR .$file_name);
                return $file_name;
            }
        }
        return false;
    }

    public static function watermark($file_name)
    {
        $image = self::FILE_DIR.$file_name;
        $watermarkImage = self::WATERMARK;
        list($imageX,$imageY) = getimagesize($image);
        list($watermarkImageX,$watermarkImageY) = getimagesize($watermarkImage);
        $newX = $imageX-$watermarkImageX;
        $newY = $imageY-$watermarkImageY;
        if($newX<0||$newY<0){//图片太小
            return;
        }
        $newimage = Image::watermark($image,$watermarkImage,[$newX,$newY]);
        $newimage->save($image);
    }
}